package 多线程.文件查找多线程125;

import java.io.File;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @program: Thread
 * description:
 * @author:yyq
 * @create: 2023-07-16 16:04
 */

public class ParallelGroupFileTask implements Runnable {
    private final String fileName;
    private final ConcurrentLinkedQueue<File> directories;
    private final Result parallelResult;
    private boolean found;

    //构造函数初始化所有的属性
    public ParallelGroupFileTask(String fileName, ConcurrentLinkedQueue<File> directories, Result parallelResult) {
        this.fileName = fileName;
        this.directories = directories;
        this.parallelResult = parallelResult;
        this.found = false;
    }

    @Override
    public void run() {
        while (directories.size() > 0) {
            File file = directories.poll(); //取出目录
            try {
                processDirectory(file, fileName, parallelResult);
                if (found) {
                    System.out.printf("%s 找到了文件：%n", Thread.currentThread().getName());
                    System.out.printf("Path : %s%n", parallelResult.getPath());
                    return;
                }
            } catch (InterruptedException e) {
                System.out.printf("%s 被中断了%n", Thread.currentThread().getName());
                return;
            }
        }
        System.out.println(Thread.currentThread().getName()+"跑完了");
    }

    //大致的搜索过程和之前的代码一样，
    private void processDirectory(File file, String fileName, Result parallelResult) throws InterruptedException {
        File[] contents = file.listFiles();

        if ((contents == null) || (contents.length == 0)) {
            return;
        }

        for (File content : contents) {
            if (content.isDirectory()) {
                processDirectory(content, fileName, parallelResult);
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException();
                }
                if (found) {
                    return;
                }

            } else {
                processFile(content, fileName, parallelResult);
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException();
                }
                if (found) {
                    return;
                }
            }
        }
    }

    //文件名称对比函数而以
    private void processFile(File content, String fileName, Result parallelResult) {
        if (content.getName().equals(fileName)) {
            parallelResult.setPath(content.getAbsolutePath());
            this.found = true;
        }
    }

    public boolean getFound() {
        return found;
    }
}

